package com.hxd.otc.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hxd.otc.mvp.base.BasePresenter;

import butterknife.ButterKnife;

public abstract class LazyFragment<P extends BasePresenter> extends BaseFragment<P> {

    protected boolean isFirstVisible = true;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (mRootView == null) {
            return;
        }
        lazyLoad();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(getLayoutId(), container, false);
            mUnbinder = ButterKnife.bind(this, mRootView);
        }
        if (mPresenter == null)
            mPresenter = createPresenter();
        return mRootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        lazyLoad();
    }


    protected void lazyLoad() {
        if (getUserVisibleHint() && isFirstVisible && mRootView != null) {
            isFirstVisible = false;
            initView();
            initData();
            initEvent();
        }
    }

    protected abstract void initData();

    protected abstract void initView();

    protected abstract void initEvent();

    protected abstract int getLayoutId();

    protected abstract P createPresenter();
}
